package com.yty.filter;


import com.yty.Utils.CurrentHolder;
import com.yty.Utils.JwtsUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebFilter("/*")
public class TokenFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器工作");
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String requestURI = httpServletRequest.getRequestURI();
        //如果是登录注册请求，直接放行
        if (requestURI.contains("login")||requestURI.contains("/register")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //从请求头中获取token
        String token = httpServletRequest.getHeader("token");
        //验证token

        try {
            Claims claims = JwtsUtils.parseToken(token);
            //将解析得token中的id放入当前线程中得ThreadLocal中
            Integer id = (Integer) claims.get("id");
            CurrentHolder.setCurrentId(id);
        } catch (Exception e) {
            //解析异常，token 无效
            e.printStackTrace();
            //设置状态码
            httpServletResponse.setStatus(401);
            return;
        }
        //令牌正常，放行
        filterChain.doFilter(servletRequest,servletResponse);
        //当本次请求结束时，清理ThreadLocal中得数据，防止内存溢出
        CurrentHolder.remove();
    }

    @Override
    public void destroy() {
        System.out.println("过滤器销毁");
    }
}
